package com.hanbang.chu_xing_gao_zhao.module;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;

import com.hanbang.chu_xing_gao_zhao.application.HttpInterfaces;
import com.hanbang.chu_xing_gao_zhao.base.BaseActivity;
import com.hanbang.chu_xing_gao_zhao.entity.UserInforData;
import com.hanbang.chu_xing_gao_zhao.utils.DbUtil;
import com.hanbang.chu_xing_gao_zhao.utils.EditHelper;
import com.hanbang.chu_xing_gao_zhao.utils.JsonHelper;
import com.hanbang.chu_xing_gao_zhao.utils.MyLocationUtils;
import com.hanbang.chu_xing_gao_zhao.utils.MyLocationUtils.locationCallback;
import com.hanbang.chu_xing_gao_zhao.utils.MyLog;
import com.hanbang.chu_xing_gao_zhao.utils.MyRequestCallBack;
import com.hanbang.chu_xing_gao_zhao.utils.MySharedPreferences;
import com.hanbang.chu_xing_gao_zhao.utils.MyToast;
import com.hanbang.chu_xing_gao_zhao.view_dynamic.DynamicActivity;
import com.hanbang.chu_xing_gao_zhao.view_information.InformationDetailsActivity;
import com.hanbang.cxgz_2.R;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

public class LogInActivity extends BaseActivity {

    private EditHelper editHelper = new EditHelper(this);

    /**
     * 我的位置
     */
    private MyLocationUtils myLocationUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        initView();
        setOnClickListener();

    }

    /*
     * 初始化view
     */
    private void initView() {

        editHelper.setEditText((EditText) findViewById(R.id.login_name), (EditText) findViewById(R.id.login_password));
        editHelper.setHintText("请正确输入手机号", "请输入密码");
        editHelper.setHintMinNumber(11, 1);


    }

    /**
     * 设置点击事件
     */
    private void setOnClickListener() {
        findViewById(R.id.user_login_register_right).setOnClickListener(onClickListener);
        findViewById(R.id.user_login_row).setOnClickListener(onClickListener);
        //忘记密码
        findViewById(R.id.login_forget_password).setOnClickListener(onClickListener);
    }

    private OnClickListener onClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            switch (v.getId()) {
                //注册
                case R.id.user_login_register_right:
                    intent.setClass(LogInActivity.this, RegisterActivity.class);
                    startActivityForResult(intent, 998);
                    break;
                case R.id.login_forget_password:
                    intent.setClass(LogInActivity.this, ForgetPasswordActivity.class);
                    startActivity(intent);
                    break;

                case R.id.user_login_row:
                    if (editHelper.check()) {

                    }
                    login();
                    break;
                default:
                    break;
            }
        }
    };

    private void login() {
        final ArrayList<String> res = editHelper.getText();
        RequestParams params = new RequestParams();
        params.addBodyParameter("telphone", res.get(0));
        params.addBodyParameter("password", res.get(1));

        httpUtils.send(HttpMethod.POST, HttpInterfaces.Login, params, new MyRequestCallBack<String>(this, "正在登录...") {

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                super.onSuccess(responseInfo);

                try {
                    JSONObject json = new JSONObject(responseInfo.result);

                    int status = json.getInt("result");
                    if (status == 0) {

                        // 把用词信息储存到数据库
                        userData = JsonHelper.parseObject(json.getJSONObject("model"), UserInforData.class);


                        if (userData != null) {
                            /**
                             * 把账号与密码存入SharedPrerences中
                             */


                            MySharedPreferences.setSharedPreferencesKeyAndValue(LogInActivity.this,
                                    MySharedPreferences.USER_DATA, "tlephone", res.get(0));
                            MySharedPreferences.setSharedPreferencesKeyAndValue(LogInActivity.this,
                                    MySharedPreferences.USER_DATA, "password", res.get(1));


                            DbUtils dbUtils = DbUtil.getDbUtils(LogInActivity.this);
                            // 把id 保存在sp
                            MySharedPreferences.setSharedPreferencesKeyAndValue(LogInActivity.this,
                                    MySharedPreferences.USER_DATA, "user_id", userData.getId());
                            try {
                                UserInforData u = dbUtils.findById(UserInforData.class, userData.getId());
                                userData.setPassword(res.get(1));
                                if (u == null) {
                                    dbUtils.save(userData);
                                } else {
                                    dbUtils.saveOrUpdate(userData);
                                }
                                MyLog.e("dbUtils", "保存成功");


                                uploadingLocation();

                            } catch (DbException e) {
                                e.printStackTrace();
                                MyToast.show(LogInActivity.this, "登录失败", Toast.LENGTH_SHORT);
                                // 登录失败把id 变成-1
                                MySharedPreferences.setSharedPreferencesKeyAndValue(LogInActivity.this,
                                        MySharedPreferences.USER_DATA, "user_id", -1);
                            }
                            finish();
                        }

                    } else {
                        MyToast.show(LogInActivity.this, "登录失败,密码或帐号错误", Toast.LENGTH_SHORT);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    MyToast.show(LogInActivity.this, "登录失败", Toast.LENGTH_LONG);

                }

            }

        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 998 && resultCode == 999) {
            ((EditText) findViewById(R.id.login_name)).setText(data.getStringExtra("phone"));
            ((EditText) findViewById(R.id.login_password)).setText(data.getStringExtra("password"));
            login();
        }
    }

    @Override
    protected void onResume() {
        // 设置顶部的标题
        setBackArrows(findViewById(R.id.bar_top_conver_classify_back));

        setTitleMore(View.GONE, View.GONE, "用户", null, null, null);

        super.onResume();
    }

    @Override
    protected void onPause() {

        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    /**
     * 获取用户的位置上传到服务器
     */
    private void uploadingLocation() {


        myLocationUtils = new MyLocationUtils(getApplicationContext());

        /**
         * 获取位置信息传给服务器
         * */
        myLocationUtils.setOnClickCallback(new locationCallback() {

            @Override
            public void onClick(String location, double longitude, double latitude) {

                getDynamicList(location, longitude, latitude, 1);

            }
        });

    }

    /**
     * 把位置上传到服务器
     *
     * @param location_name
     * @param longitude
     * @param latitude
     * @param Phonetype     手机类型
     */
    private void getDynamicList(String location_name, double longitude, double latitude, int Phonetype) {


        RequestParams params = new RequestParams();
        params.addBodyParameter("telphone", MySharedPreferences.getSharedPreferencesKeyAndValue(
                LogInActivity.this, MySharedPreferences.USER_DATA, "tlephone"));
        params.addBodyParameter("password", MySharedPreferences.getSharedPreferencesKeyAndValue(
                LogInActivity.this, MySharedPreferences.USER_DATA, "password"));

        params.addBodyParameter("location_name", location_name + "");
        params.addBodyParameter("gps", longitude + "," + latitude);
        params.addBodyParameter("os", Phonetype + "");

        httpUtils.send(HttpMethod.POST, HttpInterfaces.RememberLocation, params, new MyRequestCallBack<String>(this,
                "页面加载中...") {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                super.onSuccess(responseInfo);
                try {

                    JSONObject json = new JSONObject(responseInfo.result);

                    int result = json.getInt("Result");

                    if (result == 0) {
                        myLocationUtils.stop();
//						MyLog.i("text", "*登录后把gps,传给服务器**");// *****
                        Intent intent = new Intent(LogInActivity.this, DynamicActivity.class);
                        startActivity(intent);
                        finish();

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }
}
